package com.wzy.service.impl;

import com.wzy.mapper.UserMapper;
import com.wzy.pojo.User;
import com.wzy.service.UserService;
import com.wzy.utils.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private com.wzy.utils.IdWorker IdWorker;

    @Override
    public User getById(String id) {
        return userMapper.getUserById(id);
    }

    @Override
    public void save(User user) {
        user.setUserId(IdWorker.nextId() + "");
        user.setCreatedTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        userMapper.saveUser(user);
    }

    @Override
    public void deletedById(String id) {
        userMapper.deletedById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(User user) {
        User u = userMapper.getUserById(user.getUserId());
        user.setVersion(u.getVersion());
        user.setCreatedTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        userMapper.updateById(user);
    }

    @Override
    public Page<User> getByPage(Page<User> page) {
        //计算查询下标
        Integer pageNum = page.getPageNum();
        if (pageNum == null) {
            pageNum = 1;
            page.setPageNum(1);
        }
        Integer pageSize = page.getPageSize();
        if (pageSize == null) {
            pageSize = 10;
            page.setPageSize(10);
        }
        int index = (pageNum - 1) * pageSize;
        page.setIndex(index);
        List<User> userList = userMapper.getListByPage(page);
        int count = userMapper.getCountByPage(page);

        page.setList(userList);
        page.setTotalPage(count);

        int totalPageSiz = (int) Math.ceil(count * 1.0 / pageSize);

        page.setTotalPage(totalPageSiz);
        return page;
    }
}
